import time
import asyncio
from typing import List

# 绝对导入
from app.models.schemas import ChatMessage, ChatResponse
from app.services.mock_models import MockAIModels


class AIService:
    """
    AI Service for handling chat requests with different models
    """

    def __init__(self):
        self.mock_models = MockAIModels()

    async def process_chat(
            self,
            messages: List[ChatMessage],
            model: str,
            temperature: float = 0.7,
            max_tokens: int = 1000
    ) -> ChatResponse:
        """
        Process chat request with specified model
        """
        start_time = time.time()

        try:
            # Simulate API call delay
            await asyncio.sleep(0.1)

            # Get response from mock model
            response_content = self.mock_models.get_response(
                messages=messages,
                model=model,
                temperature=temperature
            )

            # Create response message
            response_message = ChatMessage(
                role="assistant",
                content=response_content
            )

            # Calculate processing time
            processing_time = time.time() - start_time

            # Create usage information
            usage = {
                "prompt_tokens": len(str(messages)) // 4,
                "completion_tokens": len(response_content) // 4,
                "total_tokens": (len(str(messages)) + len(response_content)) // 4
            }

            return ChatResponse(
                message=response_message,
                model=model,
                usage=usage,
                processing_time=processing_time
            )

        except Exception as e:
            # Fallback response in case of error
            error_message = ChatMessage(
                role="assistant",
                content=f"I apologize, but I encountered an error: {str(e)}"
            )

            return ChatResponse(
                message=error_message,
                model=model,
                processing_time=time.time() - start_time
            )